package persistence;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonMappingException;

import model.Email;
import model.Filter;
import model.EmailImp;
import model.MeetingInfo;
import model.MeetingMail;
import model.Template;
import model.User;
import resources.ResourceProvider;

/**
 * Persistence Manager to manage persistence
 */
public class PersistenceManager implements PersistenceManagerImp
{
    /**
     * Constructor for the class persistence manager
     */
    public PersistenceManager()
    {
 
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#persistEMail(model.EmailImp, java.lang.String)
     */
    public void persistEMail(EmailImp email, String persistPath)
    {

    	ObjectMapper mapper = new ObjectMapper();
        String slash = ResourceProvider.getFilePathSeperator();
        
        
        String dateF = email.getTime();
        String dateP = ResourceProvider.converDataFormatToPersistenceFormat(dateF);
        
        String pathWithFileName = ""; 
                
        if(email instanceof MeetingMail)
        {
            pathWithFileName = persistPath + slash + dateP + ".meeting.json";
            MeetingMail eM = (MeetingMail) email;
            
            email.setPersistencePath(pathWithFileName);

            
            try {
                mapper.writeValue(new File(pathWithFileName), eM);
            } catch (JsonMappingException e) 
            {
                e.printStackTrace();
                
            } catch(JsonGenerationException e)
            {
                e.printStackTrace();
                
            } catch(IOException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            pathWithFileName = persistPath + slash + dateP + ".json";
            Email eM = (Email) email;
            
            email.setPersistencePath(pathWithFileName);

            
            try {
                mapper.writeValue(new File(pathWithFileName), eM);
            } catch (JsonMappingException e) 
            {
                e.printStackTrace();
                
            } catch(JsonGenerationException e)
            {
                e.printStackTrace();
                
            } catch(IOException e)
            {
                e.printStackTrace();
            }
        }
        
        
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#persistUserAccount(model.User)
     */
    public void persistUserAccount(User user)
    {
        try
        {
            String seperator = ResourceProvider.getFilePathSeperator();
            String userFolderPath = ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH + user.getUserId();
            String mailboxFolderPath = userFolderPath + seperator + ResourceProvider.MAILBOX;
            String inboxFolderPath = mailboxFolderPath + seperator + ResourceProvider.INBOX;
            String outBoxFolderPath = mailboxFolderPath + seperator + ResourceProvider.OUTBOX;
            String sentFolderPath = mailboxFolderPath + seperator + ResourceProvider.SENT;
            String draftFolderPath = mailboxFolderPath + seperator + ResourceProvider.DRAFT;
            String thrashFolderPath = mailboxFolderPath + seperator + ResourceProvider.TRASH;
            String templateFolderPath = mailboxFolderPath + seperator + ResourceProvider.TEMPLATES;
            String filtersFolderPath = mailboxFolderPath + seperator + ResourceProvider.FILTERS;
            String meetingFolderPath = mailboxFolderPath + seperator + ResourceProvider.MEETING;
            
            String serverFolderPath = userFolderPath + seperator + ResourceProvider.SERVER_FOLDER;
            String serverMeetingFolderPath = serverFolderPath + seperator + ResourceProvider.SERVER_MEETING_FOLDER;

        
            
            File userFolder = new File(userFolderPath);

            // check if user account is already created
            if(!userFolder.exists())
            {
                // create user directory
                userFolder.mkdirs();
                userFolder.createNewFile();
                
                // create mailbox directory
                File mailBoxFolder = new File(mailboxFolderPath);
                mailBoxFolder.mkdirs();
                mailBoxFolder.createNewFile();
                
                // create inbox directory
                File inboxFolder = new File(inboxFolderPath);
                inboxFolder.mkdirs();
                inboxFolder.createNewFile();
                
                // create outbox directory
                File outBoxFolder = new File(outBoxFolderPath);
                outBoxFolder.mkdirs();
                outBoxFolder.createNewFile();
                
                // create sent directory
                File sentFolder = new File(sentFolderPath);
                sentFolder.mkdirs();
                sentFolder.createNewFile();
                
                // create draft directory
                File draftFolder = new File(draftFolderPath);
                draftFolder.mkdirs();
                draftFolder.createNewFile();
                
                // create thrash directory
                File thrashFolder = new File(thrashFolderPath);
                thrashFolder.mkdirs();
                thrashFolder.createNewFile();
                
                // create templates' directory
                File templateFolder = new File(templateFolderPath);
                templateFolder.mkdirs();
                templateFolder.createNewFile();
                
                // create filters' directory
                File filtersFolder = new File(filtersFolderPath);
                filtersFolder.mkdirs();
                filtersFolder.createNewFile();
                
                
                // create meetings' directory
                File meetingsFolder = new File(meetingFolderPath);
                meetingsFolder.mkdirs();
                meetingsFolder.createNewFile();
                
                // create servers' directory
                File serverFolder = new File(serverFolderPath);
                serverFolder.mkdirs();
                serverFolder.createNewFile();
                
                // create servers' meetings' directory
                File serverMeetingFolder = new File(serverMeetingFolderPath);
                serverMeetingFolder.mkdirs();
                serverMeetingFolder.createNewFile();
                
                //Creating 'access.json' file
                JsonFactory jfactory = new JsonFactory();
                JsonGenerator jGenerator = jfactory.createGenerator(new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH 
                    + seperator + user.getUserId() + seperator + "access.json"), JsonEncoding.UTF8);
                
                jGenerator.writeStartObject();
                
                 jGenerator.writeStringField("First_Name", user.getFirsName());
                 jGenerator.writeStringField("Last_Name", user.getLastName());
                 jGenerator.writeStringField("User_Id", user.getUserId());
                 jGenerator.writeStringField("Password", user.getPassword());
                 jGenerator.writeStringField("Gender", user.getGender());
                 jGenerator.writeStringField("Date", user.getBirthDay());
                 jGenerator.writeStringField("Month", user.getBirthMonth());
                 jGenerator.writeStringField("Year", user.getBirthYear());
                 
                 jGenerator.writeEndObject();
                
                 jGenerator.close();
                 
                 //Creating 'inbox_index.json' file
                 try{
                	 File inboxIndexFile = new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH
                    		 + seperator + user.getUserId() + seperator + "inbox_index.json");
                	 
                	 inboxIndexFile.createNewFile();
                	 
                 }catch(IOException e)
                 {
                	 e.printStackTrace();
                 }
                 
                 
                 
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } 
    }
    
    
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#deleteFile(java.lang.String)
     */
    public boolean deleteFile(String fileToDeletePath)
    {
        
    	File fileToDelete = new File(fileToDeletePath);
    	if(fileToDelete.isDirectory())
    		this.deleteFiles(fileToDeletePath);
        
    	return fileToDelete.delete();
    }

    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#moveToFile(java.lang.String, java.lang.String)
     */
    public void moveToFile(String sourceFilePath, String destrinationFilePath)
    {
        File file = new File(sourceFilePath);
        file.renameTo(new File(destrinationFilePath));        
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#copyFile(java.lang.String, java.lang.String)
     */
	public void copyFile(String sourceFilePath,String destrinationFilePath)
    {
        try
        {
            File sourceFile = new File(sourceFilePath);
            File destFile = new File(destrinationFilePath);
            
            if (!sourceFile.exists())
            {
                return;
            }
            
            if (!destFile.exists()) 
            {
                destFile.createNewFile();
            }
            
            FileChannel source = null;
            FileChannel destination = null;
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            
            if (destination != null && source != null)  
            {
                destination.transferFrom(source, 0, source.size());
            }
            if (source != null) 
            {
                source.close();
            }
            if (destination != null) 
            {
                destination.close();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#getEmailFilesFromFolder(java.lang.String)
     */
    public List<File> getEmailFilesFromFolder(String path)
    {
        List<File> listOfEmailFiles = new LinkedList<File>();
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles(); 
       
        for(File file : listOfFiles)
        {
            if (file.isFile() && file.getName().endsWith(".json")) 
            {
                listOfEmailFiles.add(file);
            }
        }
        
        return listOfEmailFiles;
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#writeTemplateAsFile(model.Template, java.lang.String)
     */
    public void writeTemplateAsFile(Template template, String templatePath)
    {
    	ObjectMapper mapper = new ObjectMapper();
    	String slash = ResourceProvider.getFilePathSeperator();
    	
    	try {
			mapper.writeValue(new File(templatePath + slash + template.getFileName() + ".json"), template);
    	} catch (JsonMappingException e) 
		{
			
			e.printStackTrace();
			
		} catch(JsonGenerationException e)
		{
			e.printStackTrace();
			
		} catch(IOException e)
		{
			e.printStackTrace();
		}
    	
    }
    
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#writeFilterAsFile(model.Filter, java.lang.String)
     */
    public void writeFilterAsFile(Filter filter, String filterPath)
    {
        ObjectMapper mapper = new ObjectMapper();
        String slash = ResourceProvider.getFilePathSeperator();
        
        try {
            mapper.writeValue(new File(filterPath + slash + filter.getFileName() + ".json"), filter);
        } catch (JsonMappingException e) 
        {
            
            e.printStackTrace();
            
        } catch(JsonGenerationException e)
        {
            e.printStackTrace();
            
        } catch(IOException e)
        {
            e.printStackTrace();
        }
        
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#getTemplateFromFolder(java.lang.String)
     */
    public List<Template> getTemplateFromFolder(String DirectoryPath)
    {
    	List<Template> templateList = new LinkedList<Template>();
    	File[] templateFilesList = new File(DirectoryPath).listFiles();
    	Template template;
    	
    	ObjectMapper mapper = new ObjectMapper();
    	
    	for(File templateFile : templateFilesList){
	    	try 
	    	{
				if(templateFile.getName().endsWith(".json"))
				{
				    template = mapper.readValue(templateFile, Template.class);
	                templateList.add(template);
				}	    
				
			} catch (JsonMappingException e) 
			{
				
				e.printStackTrace();
			} catch(JsonGenerationException e)
			{
				e.printStackTrace();
			} catch(IOException e)
			{
				e.printStackTrace();
			}
    	}
    	return templateList;
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#getFilterFromFolder(java.lang.String)
     */
    public List<Filter> getFilterFromFolder(String directoryPath)
    {
        List<Filter> filterList = new LinkedList<Filter>();
        File[] filterFilesList = new File(directoryPath).listFiles();
        Filter filter;
        
        ObjectMapper mapper = new ObjectMapper();
        
        for(File filterFile : filterFilesList){
            try 
            {
                if(filterFile.getName().endsWith(".json"))
                {
                    filter = mapper.readValue(filterFile, Filter.class);
                    filterList.add(filter);
                }   
                
            } catch (JsonMappingException e) 
            {   
                e.printStackTrace();
            } catch(JsonGenerationException e)
            {
                e.printStackTrace();
            } catch(IOException e)
            {
                e.printStackTrace();
            }
        }
        return filterList;
    }
    
    /**
     * iterate deep inside the given folder and add the email files into the given list
     * @param file the given root file
     * @param emailFileList the list to add the iterated files
     */
    private void iterateEmailFilesDeepInsideFolder(File file, List<File> emailFileList)
    {
        File[] files = file.listFiles();
        for(File fL : files)
        {
            if(fL.isDirectory())
            {
                iterateEmailFilesDeepInsideFolder(fL,emailFileList);
            }
            else if(fL.getName().endsWith(".json"))
            {
                emailFileList.add(fL);
            }
        }
    }

    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#getEmailFilesDeepInsideFolder(java.lang.String)
     */
    public List<File> getEmailFilesDeepInsideFolder(String path)
    {
        List<File> listOfEmailFiles = new LinkedList<File>();
        
        File file = new File(path);
        File[] listOfFiles = file.listFiles(); 
       
        for(File fL : listOfFiles)
        {
            if (fL.isFile() && fL.getName().endsWith(".json")) 
            {
                listOfEmailFiles.add(fL);
            }
            else if(fL.isDirectory())
            {
                iterateEmailFilesDeepInsideFolder(fL,listOfEmailFiles);
            }
        }
        
        return listOfEmailFiles;
    }
 
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#createFile(java.lang.String)
     */
    public void createFile(String path)
    {
        try
        {
            File newFile = new File(path);
            newFile.mkdirs();
            newFile.createNewFile();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#deleteFiles(java.lang.String)
     */
    public void deleteFiles(String path)
    {
        File file = new File(path);
        iterateAndDeleteFiles(file);
    }
    
    /**
     * iterate deep inside the given folder and delete the email files into the given list
     * @param file the file to iterate and delete contents
     */
    private void iterateAndDeleteFiles(File file)
    {
       if(file.isDirectory())
       {
           File[] files = file.listFiles();
           if(files.length > 0)
           {
            for(File fl : files)
            {
                this.iterateAndDeleteFiles(fl);
            } 
           }
           else
           {
               file.delete();
           }
       }
       else if(file.isFile())
       {
           file.delete();
       } 
       
       file.delete();
    }
    
    /**
     * check is email id registered, return true is yes, otherwise return false
     * @return the boolean value, return true if the email id registered, otherwise false
     */
    public boolean isEmailIdRegistered(String emailId)
    {
        File persistenceFile = new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH + ResourceProvider.getFilePathSeperator()+ emailId);
                
        // check if user account exists
        return persistenceFile.exists();
    }
    
    /**
     * check if the email id and password are matching, return true if yes, otherwise return false
     * @return boolean value, if valid user then return true, otherwise false
     */
    public boolean isValidUser(String emailID, String password)
    {

        String seperator = ResourceProvider.getFilePathSeperator();
        
        File persistenceFile = new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH + ResourceProvider.getFilePathSeperator()+ emailID);
        
        // validate email Id and password
        if(persistenceFile.exists())
        {
          
          JsonFactory jfactory = new JsonFactory();
            
          try
          {
              JsonParser jParser = jfactory.createParser(new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH 
                    + seperator+ emailID + seperator + "access.json"));
              
              while (jParser.nextToken() != JsonToken.END_OBJECT) 
              {
                  String name = jParser.getCurrentName();
                  if ("Password".equals(name)) 
                  {
                    jParser.nextToken();
                    String passW = jParser.getText();
                    
                    return passW.equals(password);
                  }
              }
          }
          catch (JsonParseException e)
          {
              e.printStackTrace();
          }
          catch (IOException e)
          {
              e.printStackTrace();
          }
        }
        
        return false;
    }
    
    /**
     * convert JSON to String
     * @param jsonFile the given JSON file
     * @return the String representation of the JSON content
     */
    @SuppressWarnings("unchecked")
	private String jsonToString(File jsonFile)
    {
    	ObjectMapper mapper =new ObjectMapper();
    	Map<String, Map<String,String>> onePair= new HashMap<String, Map<String,String>>();
		try {
			
			onePair = mapper.readValue(jsonFile, HashMap.class);
			
		} catch (JsonMappingException e) 
		{
			e.printStackTrace();
			
		} catch(JsonGenerationException e)
		{
			e.printStackTrace();
			
		} catch(IOException e)
		{
			e.printStackTrace();
		}
		
		String finalString = "";
		for(Map.Entry<String, Map<String, String>> oneEntry : onePair.entrySet())
			finalString+= "~" + oneEntry.getValue();
		
    	return finalString;
    }
    
    
    /**
     * A method to update the index of all email-JSON files present in the inbox folder.
     * @param user User parameter is the user object for whom the index file should be updated.
     * @return returns a Map<String,String> object version of the json file.
     */
    public Map<String,String> updateInboxIndexFileOf(String user)
    {
    	String seperator = ResourceProvider.getFilePathSeperator();
        String inboxFolderPath = ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH + user+ seperator + ResourceProvider.MAILBOX + seperator + ResourceProvider.INBOX;
        List<File> inboxEmailFilesList = getEmailFilesDeepInsideFolder(inboxFolderPath);
        
    	Map<String,String> inboxAsMap = new HashMap<String,String>();
    	
    	File inboxIndexFile = new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH
         		 + seperator + user + seperator + "inbox_index.json");
    	
    	
    	try
    	{
    		JsonFactory jfactory = new JsonFactory();
            JsonGenerator jGenerator = jfactory.createGenerator(inboxIndexFile, JsonEncoding.UTF8);
            jGenerator.writeStartObject();
            String tempFilePath ="";
            
            for(File emailFile: inboxEmailFilesList)
	    	{
	    		String oneReadEmail = jsonToString(emailFile);
	    		tempFilePath = emailFile.getPath().replace(inboxFolderPath +ResourceProvider.getFilePathSeperator(), "");
	    		
	    		inboxAsMap.put(tempFilePath, oneReadEmail);
	    		jGenerator.writeStringField(tempFilePath , oneReadEmail);
	    	}
            
            jGenerator.writeEndObject();
	        jGenerator.close();
    	}
    	catch(IOException e)
    	{
    		e.printStackTrace();
		}
    	
    	return inboxAsMap;
    }
    
    /**
     * A method that returns a list of matched Strings given a query.
     * @param user the user
     * @param query The search query as a String.
     * @param isRegEx
     * @return List of the email file names as a list of String object.
     */
    private List<String> searchInboxIndexFile(String user, String query, boolean isRegEx)
    {
    	
    	Map<String,String> indexFileMap = new HashMap<String, String>(); 
    	indexFileMap = this.updateInboxIndexFileOf(user);
    	Pattern searchPattern;
    	
    	if(isRegEx)
    	{
    		searchPattern = Pattern.compile(query);    		
    	}
    	else
    	{
    		String regex = query.replaceAll("[\\{\\}\\(\\)\\[\\]~\\*\\^\\$\\:\\=\\!\\+\\-\\\\]+", "`").trim();
        	searchPattern = Pattern.compile("(?=.*"+regex+".*)", Pattern.CASE_INSENSITIVE);    		
    	}
    	
    	List<String> matchedFileNameList = new LinkedList<String>();
    	
    	for(Map.Entry<String, String> oneEntry : indexFileMap.entrySet())
    	{
    		Matcher matcher = searchPattern.matcher(oneEntry.getValue());
    		if(matcher.find())
    			matchedFileNameList.add(oneEntry.getKey());
    	}
    	
    	return matchedFileNameList; 
    }
    
    
    
    /*
     *  (non-Javadoc)
     * @see persistence.IPersistenceManager#getSearchResult(java.lang.String, java.lang.String)
     */
    public List<File> getSearchResult(String user, String query, boolean isRegEx)
    {
    	updateInboxIndexFileOf(user);
    	List<File> searchResult = new LinkedList<File>();
        String seperator = ResourceProvider.getFilePathSeperator();
        String inboxFolderPath = ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH + user+ seperator 
                 + ResourceProvider.MAILBOX + seperator + ResourceProvider.INBOX;
        
        List<String> resultFileList = this.searchInboxIndexFile(user, query, isRegEx);
        for(String result : resultFileList)
        {
            
            File email = new File(inboxFolderPath + seperator + result);
            searchResult.add(email);
        }
         return searchResult;
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#getAdvancedSearchResult(java.lang.String, java.lang.String, int)
     */
    public Map<String,File> getAdvancedSearchResult(String user, String query, int SearchType)
    {
    	updateInboxIndexFileOf(user);
    	Map<String,File> searchResult = new HashMap<String,File>();
        
    	String separator = ResourceProvider.getFilePathSeperator();
        String indexFilePath = ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH
        		 + separator + user + separator + "inbox_index.json";
        
        String inboxFolderPath = ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH + user+ separator 
                + ResourceProvider.MAILBOX + separator + ResourceProvider.INBOX + separator;
        
        
        Map<String, String> indexFileMap = this.emailJsonToMap(indexFilePath);
        
        Pattern pattern = Pattern.compile(".*"+query+".*",Pattern.CASE_INSENSITIVE);
        
        for(Map.Entry<String, String> onePair: indexFileMap.entrySet())
        {
        	switch(SearchType)
        	{
        		case ResourceProvider.SEARCH_EMAIL_FROM:
        			if(onePair.getValue().split("~").length==11)
        			{
        				if( onePair.getValue().split("~")[10].equalsIgnoreCase(query) )
            				searchResult.put(onePair.getKey(), new File(inboxFolderPath + onePair.getKey()));
            		}
        			else
        			{
	        			if( onePair.getValue().split("~")[ResourceProvider.SEARCH_EMAIL_FROM].equalsIgnoreCase(query) )
	        				searchResult.put(onePair.getKey(), new File(inboxFolderPath + onePair.getKey()));	        			
        			}
        			break;
        		
        		case ResourceProvider.SEARCH_EMAIL_SUBJECT:
        			
        			if(onePair.getValue().split("~").length==11)
        			{
        				Matcher matcher = pattern.matcher(onePair.getValue().split("~")[7]);
            			if(matcher.find())
            				searchResult.put(onePair.getKey(), new File(inboxFolderPath + onePair.getKey()));
        			}
        			else
        			{
        				Matcher matcher = pattern.matcher(onePair.getValue().split("~")[ResourceProvider.SEARCH_EMAIL_SUBJECT]);
            			if(matcher.find())
            				searchResult.put(onePair.getKey(), new File(inboxFolderPath + onePair.getKey()));
        			}
        			break;
            		
        		case ResourceProvider.SEARCH_EMAIL_MESSAGE:
        			if(onePair.getValue().split("~").length==11)
        			{
        				for(String oneWord : query.split(","))
            			{
            				pattern = Pattern.compile(oneWord);
            				Matcher matcher = pattern.matcher(onePair.getValue().split("~")[6]);
            				if(matcher.find())
            					searchResult.put(onePair.getKey(), new File(inboxFolderPath + onePair.getKey()));
            				break;
            			}
        			}
        			else
        			{
        				for(String oneWord : query.split(","))
            			{
            				pattern = Pattern.compile(oneWord);
            				Matcher matcher = pattern.matcher(onePair.getValue().split("~")[ResourceProvider.SEARCH_EMAIL_MESSAGE]);
            				if(matcher.find())
            					searchResult.put(onePair.getKey(), new File(inboxFolderPath + onePair.getKey()));
            				break;
            			}
        			}
        			break;
    		}
        }
    		
    	return searchResult;
    }
    
    /**
     * A method to convert read files to HashMap-email object.
     * @param path the full path to the email file.
     * @return returns a HashMap object equivalent to the read JSON file path passed as parameter. 
     */
    @SuppressWarnings("unchecked")
	public HashMap<String,String> emailJsonToMap(String path)
    {
    	ObjectMapper mapper = new ObjectMapper();
    	HashMap<String,String> oneEmail = new HashMap<String,String>();
    	
    	try 
    	{	
    		oneEmail = mapper.readValue(new File(path), HashMap.class);
		} 
    	catch (JsonMappingException e) 
		{
			e.printStackTrace();
		} 
    	catch(JsonGenerationException e)
		{
			e.printStackTrace();
		} 
    	catch(IOException e)
		{
			e.printStackTrace();
		}
		
    	return oneEmail;
    }
   
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#emailJsonToEmailImp(java.lang.String)
     */
    public EmailImp emailJsonToEmailImp(String path)
    {
    	ObjectMapper mapper = new ObjectMapper();
    	EmailImp oneEmailMap = null;
    	
    	if(path.endsWith(".meeting.json"))
    	{
    		try 
        	{	
        		 oneEmailMap = (EmailImp) mapper.readValue(new File(path), MeetingMail.class);
    		} 
        	catch (JsonMappingException e) 
    		{
    			e.printStackTrace();
    		} 
        	catch(JsonGenerationException e)
    		{
    			e.printStackTrace();
    		} 
        	catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    	else
    	{
    		try 
        	{	
        		 oneEmailMap = (EmailImp) mapper.readValue(new File(path), Email.class);
    		} 
        	catch (JsonMappingException e) 
    		{
    			e.printStackTrace();
    		} 
        	catch(JsonGenerationException e)
    		{
    			e.printStackTrace();
    		} 
        	catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    	
    	return oneEmailMap;
    }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#persistMeetingInfo(model.MeetingInfo, java.lang.String)
     */
    public void persistMeetingInfo(MeetingInfo info, String path)
    {
        ObjectMapper mapper = new ObjectMapper();
        String slash = ResourceProvider.getFilePathSeperator();
        
        try {
            mapper.writeValue(new File(path + slash + info.meetingID + ".json"), info);
        } catch (JsonMappingException e) 
        {
            
            e.printStackTrace();
            
        } catch(JsonGenerationException e)
        {
            e.printStackTrace();
            
        } catch(IOException e)
        {
            e.printStackTrace();
        }
        
    }


    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#getPersistMeetingInfo(java.lang.String)
     */
    @Override
    public List<MeetingInfo> getPersistMeetingInfo(String meetingFolderPath)
    {
        List<MeetingInfo> meetingInfoList = new LinkedList<MeetingInfo>();
        File[] files = new File(meetingFolderPath).listFiles();
        MeetingInfo template;
        
        ObjectMapper mapper = new ObjectMapper();
        
        for(File meetingInfoFile : files)
        {
            try 
            {
                if(meetingInfoFile.getName().endsWith(".json"))
                {
                    template = mapper.readValue(meetingInfoFile, MeetingInfo.class);
                    meetingInfoList.add(template);
                }       
                
            } catch (JsonMappingException e) 
            {
                
                e.printStackTrace();
            } catch(JsonGenerationException e)
            {
                e.printStackTrace();
            } catch(IOException e)
            {
                e.printStackTrace();
            }
        }
        return meetingInfoList;    
      }
    
    /*
     * (non-Javadoc)
     * @see persistence.PersistenceManagerImp#getMeetingInfo(java.lang.String)
     */
    public MeetingInfo getMeetingInfo(String meetingPath)
    {
        MeetingInfo meeting = null;
        
        ObjectMapper mapper = new ObjectMapper();
        
            try 
            {
                File file = new File(meetingPath);
                if(file.getName().endsWith(".json"))
                {
                    meeting = mapper.readValue(file, MeetingInfo.class);
                }       
                
            } catch (JsonMappingException e) 
            {
                
                e.printStackTrace();
            } catch(JsonGenerationException e)
            {
                e.printStackTrace();
            } catch(IOException e)
            {
                e.printStackTrace();
            }
        return meeting;    
      }
}
